<template>
  <div class="wechat-login">
    <h2>微信扫码登录</h2>
    <div class="qr-container">
      <div v-if="loginLoading" class="loading">
        <div class="spinner"></div>
        <p>正在生成二维码...</p>
      </div>
      <div v-else-if="qrCode" class="qr-code">
        <img :src="qrCode" alt="微信登录二维码" />
        <p class="qr-tip">请使用微信扫描二维码登录</p>
        <div class="status-indicator" :class="status" :style="{ color: statusColor }">
          <span class="status-icon">{{ statusIcon }}</span>
          <span class="status-text">{{ statusText }}</span>
          <div v-if="status === 'waiting' && countdown > 0" class="countdown">
            有效期：{{ formatCountdown }}
          </div>
        </div>
      </div>
      <div v-else class="error">
          <p>{{ errorMessage || '二维码生成失败，请重试' }}</p>
          <button @click="generateQR" class="retry-btn">重新生成</button>
          <button v-if="process.env.NODE_ENV === 'development'" @click="quickLogin" class="quick-login-btn">快速登录（开发）</button>
        </div>
    </div>
    <div class="alternative-login">
      <p>或者</p>
      <button @click="goBack" class="login-link">使用账号密码登录</button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { useUserStore } from '../stores/user';
import { useRouter } from 'vue-router';
import QRCode from 'qrcode';

// 初始化store和router
const userStore = useUserStore();
const router = useRouter();

    const qrCode = ref('');
    const qrToken = ref(''); // 二维码token，用于状态检查
    const status = ref('waiting'); // waiting, scanned, confirmed, expired, error
    const statusText = ref('请使用微信扫描二维码登录');
    const isLoading = ref(false);
    const errorMessage = ref('');
    const countdown = ref(300); // 二维码有效期倒计时（秒）
    let checkInterval = null;
    let countdownInterval = null;

    // 计算状态图标
    const statusIcon = computed(() => {
      switch (status.value) {
        case 'waiting':
          return '📱';
        case 'scanned':
          return '👀';
        case 'confirmed':
          return '✅';
        case 'expired':
          return '⏰';
        case 'error':
          return '❌';
        default:
          return '📱';
      }
    });

    // 计算状态颜色
    const statusColor = computed(() => {
      switch (status.value) {
        case 'waiting':
          return '#666';
        case 'scanned':
          return '#f39c12';
        case 'confirmed':
          return '#27ae60';
        case 'expired':
          return '#e74c3c';
        case 'error':
          return '#e74c3c';
        default:
          return '#666';
      }
    });

    // 格式化倒计时
    const formatCountdown = computed(() => {
      const minutes = Math.floor(countdown.value / 60);
      const seconds = countdown.value % 60;
      return `${minutes}:${seconds.toString().padStart(2, '0')}`;
    });

    const loginLoading = computed(() => userStore.loginLoading || isLoading.value);

    // 生成二维码
    const generateQR = async () => {
      isLoading.value = true;
      errorMessage.value = '';
      
      try {
        const qrData = await userStore.generateWechatQR();
        qrCode.value = qrData.qrCode;
        qrToken.value = qrData.token || qrData.qrToken || '';
        status.value = 'waiting';
        statusText.value = '请使用微信扫描二维码登录';
        countdown.value = qrData.expiresIn || 300; // 默认5分钟
        
        // 开始检查扫码状态和倒计时
        startStatusCheck();
        startCountdown();
      } catch (error) {
        console.error('生成二维码失败:', error);
        status.value = 'error';
        if (error.response) {
          switch (error.response.status) {
            case 429:
              errorMessage.value = '请求过于频繁，请稍后再试';
              break;
            case 500:
              errorMessage.value = '服务器错误，请稍后重试';
              break;
            default:
              errorMessage.value = error.response.data?.message || '生成二维码失败，请重试';
          }
        } else if (error.code === 'NETWORK_ERROR') {
          errorMessage.value = '网络连接失败，请检查网络设置';
        } else {
          errorMessage.value = '生成二维码失败，请重试';
        }
        statusText.value = '生成二维码失败';
      } finally {
        isLoading.value = false;
      }
    };

    // 检查扫码状态
    const checkScanStatus = async () => {
      if (!qrToken.value) {
        return;
      }
      
      try {
        const result = await userStore.checkWechatScanStatus(qrToken.value);
        
        switch (result.status) {
          case 'scanned':
            if (status.value !== 'scanned') {
              status.value = 'scanned';
              statusText.value = '扫描成功，请在手机上确认登录';
            }
            break;
          case 'confirmed':
            status.value = 'confirmed';
            statusText.value = '登录成功，正在跳转...';
            stopStatusCheck();
            stopCountdown();
            
            // 如果返回了用户信息，更新store
            if (result.userInfo) {
              userStore.setUserInfo(result.userInfo);
            }
            
            // 登录成功后跳转
            setTimeout(() => {
              const redirectPath = router.currentRoute.value.query.redirect || '/';
              router.push(redirectPath);
            }, 1500);
            break;
          case 'expired':
            status.value = 'expired';
            statusText.value = '二维码已过期，请刷新重试';
            stopStatusCheck();
            stopCountdown();
            break;
          case 'cancelled':
            status.value = 'waiting';
            statusText.value = '用户取消登录，请重新扫描';
            break;
          case 'error':
            status.value = 'error';
            statusText.value = result.message || '登录失败，请重试';
            errorMessage.value = result.message || '登录过程中发生错误';
            stopStatusCheck();
            break;
        }
      } catch (error) {
        console.error('检查扫码状态失败:', error);
        // 网络错误不改变状态，继续检查
        if (error.code !== 'NETWORK_ERROR') {
          status.value = 'error';
          statusText.value = '检查登录状态失败';
          errorMessage.value = '网络连接异常，请检查网络后重试';
          stopStatusCheck();
        }
      }
    };

    // 开始状态检查
    const startStatusCheck = () => {
      if (checkInterval) {
        clearInterval(checkInterval);
      }
      // 立即检查一次，然后每2秒检查一次
      checkScanStatus();
      checkInterval = setInterval(checkScanStatus, 2000);
    };

    // 停止状态检查
    const stopStatusCheck = () => {
      if (checkInterval) {
        clearInterval(checkInterval);
        checkInterval = null;
      }
    };

    // 开始倒计时
    const startCountdown = () => {
      if (countdownInterval) {
        clearInterval(countdownInterval);
      }
      countdownInterval = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
          status.value = 'expired';
          statusText.value = '二维码已过期，请刷新重试';
          stopStatusCheck();
          stopCountdown();
        }
      }, 1000);
    };

    // 停止倒计时
    const stopCountdown = () => {
      if (countdownInterval) {
        clearInterval(countdownInterval);
        countdownInterval = null;
      }
    };

    // 刷新二维码
    const refreshQRCode = () => {
      stopStatusCheck();
      stopCountdown();
      generateQR();
    };

    // 返回登录页
    const goBack = () => {
      stopStatusCheck();
      stopCountdown();
      router.push('/login');
    };

    // 快速登录（演示用）
    const quickLogin = async () => {
      if (process.env.NODE_ENV === 'development') {
        try {
          // 模拟微信登录成功
          const mockUserInfo = {
            id: 'wechat_user_123',
            username: 'wechat_user',
            nickname: '微信用户',
            avatar: '/img/thumb.jpg',
            email: 'wechat@example.com'
          };
          
          userStore.setUserInfo(mockUserInfo);
          status.value = 'confirmed';
          statusText.value = '登录成功，正在跳转...';
          
          setTimeout(() => {
            const redirectPath = router.currentRoute.value.query.redirect || '/';
            router.push(redirectPath);
          }, 1000);
        } catch (error) {
          console.error('快速登录失败:', error);
        }
      }
    };

    // 组件挂载时生成二维码
    onMounted(() => {
      generateQR();
    });

// 组件卸载时清理定时器
onUnmounted(() => {
  stopStatusCheck();
  stopCountdown();
});
</script>

<style scoped>
.wechat-login {
  max-width: 400px;
  margin: 0 auto;
  padding: 40px 30px;
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
  text-align: center;
}

.wechat-login h2 {
  margin-bottom: 30px;
  font-size: 28px;
  font-weight: 700;
  background: linear-gradient(45deg, #00d4ff, #ff6b6b);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.qr-container {
  margin-bottom: 30px;
}

.loading {
  padding: 40px;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(255, 255, 255, 0.1);
  border-left: 4px solid #00d4ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.qr-code img {
  width: 200px;
  height: 200px;
  border: 2px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  background: white;
  padding: 10px;
}

.qr-tip {
  margin: 15px 0;
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
}

.status-indicator {
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  margin-top: 15px;
}

.status-indicator.waiting {
  background: rgba(59, 130, 246, 0.2);
  color: #3b82f6;
  border: 1px solid rgba(59, 130, 246, 0.3);
}

.status-indicator.scanned {
  background: rgba(251, 191, 36, 0.2);
  color: #fbbf24;
  border: 1px solid rgba(251, 191, 36, 0.3);
}

.status-indicator.confirmed {
  background: rgba(34, 197, 94, 0.2);
  color: #22c55e;
  border: 1px solid rgba(34, 197, 94, 0.3);
}

.status-indicator.expired {
  background: rgba(239, 68, 68, 0.2);
  color: #ef4444;
  border: 1px solid rgba(239, 68, 68, 0.3);
}

.error {
  padding: 40px;
  color: rgba(255, 255, 255, 0.7);
}

.retry-btn {
  margin-top: 15px;
  padding: 10px 20px;
  background: linear-gradient(45deg, #00d4ff, #ff6b6b);
  border: none;
  border-radius: 8px;
  color: white;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.retry-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(0, 212, 255, 0.3);
}

.alternative-login {
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  padding-top: 20px;
}

.alternative-login p {
  color: rgba(255, 255, 255, 0.5);
  margin-bottom: 10px;
  font-size: 14px;
}

.login-link {
  color: #00d4ff;
  text-decoration: none;
  font-weight: 500;
  transition: color 0.3s ease;
}

.login-link:hover {
  color: #ff6b6b;
}

@media (max-width: 768px) {
  .wechat-login {
    margin: 20px;
    padding: 30px 20px;
  }
  
  .wechat-login h2 {
    font-size: 24px;
  }
  
  .qr-code img {
    width: 180px;
    height: 180px;
  }
}
</style>